/*
 * Copyright (c) 2021 The red-star Project
 *
 * Licensed under the Apache License, version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inyourcode.core.db.iml;

import com.inyourcode.core.db.api.IDBResource;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author JackLei
 */
public class MutilpleResource implements IDBResource {
    private RedisResource redisResource;
    private MongoResource mongoResource;

    public MutilpleResource(RedisResource redisResource, MongoResource mongoResource) {
        this.redisResource = redisResource;
        this.mongoResource = mongoResource;
    }

    @Override
    public Map<String, byte[]> load(String key) {
        Map<String, byte[]> dataFromRedis = redisResource.load(key);
        if (!CollectionUtils.isEmpty(dataFromRedis)) {
            return dataFromRedis;
        }

        Map<String, byte[]> dataFromMongo = mongoResource.load(key);
        if (CollectionUtils.isEmpty(dataFromMongo)) {
            return new HashMap<>();
        }
        return dataFromMongo;
    }

    @Override
    public void save(String key, Map<String, byte[]> update) {
        redisResource.save(key, update);
        mongoResource.save(key, update);
    }

    public void cacheDataOptExpire(boolean clear, String key, int expireTime) {
        this.redisResource.cacheDataOptExpire(clear, key, expireTime);
    }
}
